package com.hmdp.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryTypeList() {
        //构造key
        String typeKey = RedisConstants.CACHE_SHOP_TYPE_KEY;
        ListOperations<String, String> opsForList = stringRedisTemplate.opsForList();
        List<String> shopTypeList = opsForList.range(typeKey, 0, -1);
        if (CollUtil.isNotEmpty(shopTypeList)){
            //将list里的String转为ShopType
            List<ShopType> collect = shopTypeList.stream()
                    .map(s -> JSONUtil.toBean(s, ShopType.class))
                    .sorted(Comparator.comparing(ShopType::getSort))
                    .collect(Collectors.toList());
            return Result.ok(collect);
        }
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //存入redis
        if (CollUtil.isEmpty(typeList)){
            return Result.fail("店铺不存在");
        }
        opsForList.rightPushAll(typeKey,typeList.stream()
                .sorted(Comparator.comparingInt(ShopType::getSort))
                .map(JSONUtil::toJsonStr)
                .collect(Collectors.toList()));
        stringRedisTemplate.expire(typeKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(typeList);
    }
}
